package com.hdd.art.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 作者： fangzehua
 * 时间： 2021/6/19 13:29
 *
 * @Version: 1.0
 * @Desc 类描述信息
 */
public class ThreadUtil {
    private static final Logger log   = LoggerFactory.getLogger(ThreadUtil.class);

    public static final ExecutorService pool  = Executors.newFixedThreadPool(CommonUtil.getCpuSize() * 4);

    public static ReentrantLock lock  = new ReentrantLock();

    public static HashMap<Integer, ExecutorService> pools = new HashMap<Integer, ExecutorService>();

    public static ExecutorService getPools(int i) {
        try
        {
            lock.lock();
            ExecutorService pool = pools.get(i);
            if (pool == null)
            {
                pool = Executors.newFixedThreadPool(CommonUtil.getCpuSize() * 10);
                pools.put(i, pool);
                log.debug("创建新的线程池...{}...", i);
            }
            return pool;
        }
        finally
        {
            lock.unlock();
        }
    }

    public static void destroy() {
        shutdownThreadPool(pool, "main");
        for (Integer i : pools.keySet())
        {
            shutdownThreadPool(pools.get(i), "main-" + i);
        }
        pools.clear();
    }

    /**
     * 优雅关闭线程池
     *
     * @param threadPool
     * @param alias
     */
    private static void shutdownThreadPool(ExecutorService threadPool, String alias) {
        log.info("Start to shutdown the thead pool: {}", alias);
        threadPool.shutdown(); // 使新任务无法提交.
        try
        {
            // 等待未完成任务结束
            if (!threadPool.awaitTermination(60, TimeUnit.SECONDS))
            {
                threadPool.shutdownNow(); // 取消当前执行的任务
                log.warn("Interrupt the worker, which may cause some task inconsistent. Please check the biz logs.");

                // 等待任务取消的响应
                if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) log.error("Thread pool can't be shutdown even with interrupting worker threads, which may cause some task inconsistent. Please check the biz logs.");
            }
        }
        catch (InterruptedException ie)
        {
            // 重新取消当前线程进行中断
            threadPool.shutdownNow();
            log.error("The current server thread is interrupted when it is trying to stop the worker threads. This may leave an inconcistent state. Please check the biz logs.");

            // 保留中断状态
            Thread.currentThread().interrupt();
        }

        log.info("Finally shutdown the thead pool: {}", alias);
    }
}

